<?php

namespace App\Service\Customer;


use App\Common\Result;
use App\Models\Customer\CustomerModel;
use App\Models\Customer\CustomerOauthModel;
use DB;

class CustomerService
{
    /**
     * 创建用户
     * @param $email
     * @param $password
     * @param string $nickname
     * @return array|bool
     */
    public static function createUser(array $info)
    {
        $email = isset($info['email'])? $info['email']:'';
        $password = isset($info['password'])? Result::md5_pwd($info['password']) : '';
        $nickname = isset($info['nickname'])?$info['nickname']:self::creatRandNickname();
        $uid = isset($info['uid'])? $info['uid']: self::createUid();
        $imgurl = $info['headimgurl'];

        $input = [
            'uid' => $uid,
            'email' => $email,
            'password' => $password,
            'nickname' => $nickname,
            'headimgurl' => $imgurl,
        ];

       if( !CustomerModel::create($input) ){
           return false;
       }
           return $input;
    }

    /**
     * 检查密码
     * @param $email
     * @param $password
     * @return array
     */
    public static function checkPwd($email, $password)
    {
        $responce = [
            'code'=>201,
            'result'=>false,
            'message'=>'网络错误'
        ];

        $input = [
            'email'=>$email,
            'password'=>$password,
        ];
        $customerinfo = CustomerModel::where($input)->first();
        $findUser = self::findUser(['email'=>$email]);

        if(!$findUser){
            $responce['code'] = '-6';
            $responce['message'] = '没有此账号，请注册';
        }else{

            if(!$customerinfo){
                $responce['code'] = '-7';
                $responce['message'] = '密码错误';
            }else{
                $responce['result'] = true;
                $responce['data'] = $customerinfo->toArray();
            }
        }

        return $responce;
    }

    /**
     * 根据uid查找用户
     */
    public static function findUser(array $info)
    {
        return CustomerModel::where($info)->first();
    }


    /**
     *刷新用户信息
     */
    public static function updUser($uid, array $info)
    {
        //\DB::beginTransaction();

        $customeroauth = CustomerOauthService::updOauth($uid, $info);

        if(CustomerModel::where('uid',$uid)->update($info) && $customeroauth){
            \DB::commit();
            $info['uid'] = $uid;
            return $info;
        }else{
            \DB::rollback();
            return false;
        }
    }

    /**
     * 创建第三方登入用户
     */
    public static  function createOauth(array $data)
    {
        $responce = [
            'result' => true,
            'message' => ''
        ];
        \DB::beginTransaction();
        $createcustomer = self::createUser([
            'nickname' => $data['nickname'],
            'headimgurl' => $data['headimgurl']
        ]);
        $data['uid'] = $createcustomer['uid'];
        $createoauth = CustomerOauthModel::create($data);
        if($createcustomer && $createoauth){
            \DB::commit();
        }else{
            $responce['result'] = false;
            $responce['message'] = '登入失败';
            \DB::rollback();
            return false;
        }
        $responce['uid'] = $data['uid'];
        $responce['nickname'] = $data['nickname'];
        $responce['headimgurl'] = $data['headimgurl'];
        return $responce;
    }
    /**
     * 生成uid
     * @return string
     */
    public static function createUid()
    {
        $uid='sj_'.time().str_pad(mt_rand(0, pow(10, 4) - 1), 4, '0', STR_PAD_LEFT);
        return $uid;
    }

    /**
     * 生成随机用户昵称
     */
    public static function creatRandNickname()
    {
        $nick_num = DB::table('lsj_config')->where('id',2)->select('value')->first();
        $nickname = "普通用户".$nick_num->value;
        DB::table('lsj_config')->where('id',2)->increment('value');

        return $nickname;
    }
    /**
     * 修改用户信息
     */
    public static function changeUser($uid , array $data)
    {
        try{
            $res = CustomerModel::where('uid', "$uid")
                ->update($data);
        } catch (Exception $e){
            ServiceLog::record("sqlerror.txt",$e->getMessage(),"sql_error");
        }

        if(!$res){
            return false;
        }
        return true;
    }
	//介绍
	public static function setIntroduce($uid,$introduce = '作者很懒,什么也没留下')
    {
        $data = [
            'introduce'=>$introduce
        ];
        return CustomerModel::where('uid',$uid)->update($data);
    }

    //增加余额
    public static function incBalance($uid,$money)
    {
        $result = DB::table('lsj_user')
            ->where('uid',$uid)
            ->increment('balance',$money);
        return $result;
    }

    //获取昵称有没有重名
    public static function getNameNum()
    {

    }

    /**
     * 登入自动关注小贩
     */
    public static function UserLoginFollow($uid)
    {
        $is_follow = CustomerRelateService::findFollow($uid, 'sj_14994146054001');
        if(!$is_follow)
            CustomerRelateService::addFollow([
                'uid' => $uid,
                'fuid' => 'sj_14994146054001'
            ]);
        return true;
    }

    /**
     * uid in
     */
    public static function userNameAndHeadWhereIn($data = [])
    {
        $users = CustomerModel::select('nickname','headimgurl','uid')
            ->whereIn('uid',$data)->get();
        return $users;
    }
}